#!/usr/bin/env python3
"""
将表格中地址为 xxxx-xxxx 的行，地址只保留起始，长度保持，范围列如有区间则清空。
用法：python3 scripts/fix_address_range.py config/protocols/monet/monet.md
"""
import sys, re

if len(sys.argv) < 2:
    print("usage: fix_address_range.py file.md")
    sys.exit(2)

path = sys.argv[1]
with open(path, 'r', encoding='utf-8') as f:
    lines = f.readlines()

out = []
changed = False
row_pat = re.compile(r'^\s*\|.*\|\s*$')
for line in lines:
    if row_pat.match(line):
        cells = [c.strip() for c in line.strip().split('|')[1:-1]]
        if len(cells) < 5:
            out.append(line)
            continue
        # 地址列
        addr = cells[0]
        m = re.match(r'^(\d+)-(\d+)$', addr)
        if m:
            cells[0] = m.group(1)
            # 范围列（第5列，索引4）如有区间则清空
            if '-' in cells[4] or '~' in cells[4] or '(' in cells[4]:
                cells[4] = ''
            new_line = '| ' + ' | '.join(cells) + ' |\n'
            out.append(new_line)
            changed = True
            continue
    out.append(line)

if changed:
    bak = path + '.bak'
    with open(bak, 'w', encoding='utf-8') as f:
        f.writelines(lines)
    with open(path, 'w', encoding='utf-8') as f:
        f.writelines(out)
    print(f"Fixed address ranges in {path}; backup at {bak}")
else:
    print(f"No changes needed for {path}")
